<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '保存并继续',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并关闭',
      icon: '',
      type: 'primary',
      hidden: !isEdit || !!data.form.associationBillNo,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createByName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
    {
      label: '完成时间',
      value: 'completedTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12 full flex-c">
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="单据单号" prop="productTakeStockNo">
              <ElInputBox :data="form" dataName="productTakeStockNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据状态" prop="productTakeStockState">
              <ElSelectBox :data="form" dataName="productTakeStockState" :options="options.state" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据备注" prop="productTakeStockRemark" class="wAuto">
              <ElInputBox :data="form" dataName="productTakeStockRemark" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="单据明细" isTop isAuto>
          <template #btn>
            <el-link type="primary" @click="exportBtn" icon="Download">导出明细</el-link>
          </template>
          <el-auto-resizer class="full">
            <template #default="{ height }">
              <TableBoxMxVirtualized :height="height" :data="{
                filter: (el: any) => {
                  const search = data.search
                  return (el.takeStockResult === search.typeCode || search.typeCode === -1) && (!search.productName || search.productName.includes(el.productName))
                },
                disabled: !isEdit,
                tbody: form.details,
                search: data.search,
                thead: form.productTakeStockState === 0 ? data.thead.filter((el: any) => !['盘点单价', '盘点总价'].includes(el.label)) : data.thead,
                form: form
              }">
                <template #headL>
                  <ElInputBox :data="data.search" dataName="productName" :width="300" placeholder="产品名称" />
                </template>
                <template #headR>
                  <el-radio-group v-model="data.search.typeCode">
                    <el-radio-button :label="`${item.label}(${getNumber(item.value)})`" :value="item.value"
                      v-for="item in data.type" />
                  </el-radio-group>
                </template>
              </TableBoxMxVirtualized>
            </template>
          </el-auto-resizer>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { useListComponent } from '../pageTs'; // 引入逻辑
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { dataInfo, options } = useListComponent();
const router = useRouter();
const { proxy } = getCurrentInstance() as any;
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    productTakeStockCode: '', // 	唯一code
    productTakeStockNo: '', // 	盘点单号
    productTakeStockState: 0, // 盘点单据状态：1盘点中（待确认）；2盘点完成（已确认）
    productTakeStockRemark: '', // 备注
    details: []
  },
  search: {
    typeCode: -1,
    productName: '',
  },
  thead: [
    {
      label: '产品名称',
      prop: 'productName',
      align: 'left', // 默认居中对齐
      width: 200
    },
    {
      label: '产品型号',
      prop: 'productSpecificationName',
      align: 'left', // 根据提供的信息指定左对齐
      width: 200
    },
    {
      label: '客户名称',
      prop: 'customerName',
      align: 'center', // 默认居中对齐
      width: 120
    },
    {
      label: '印刷版面',
      prop: 'productLayout',
      align: 'center', // 默认居中对齐
      width: 80
    },
    {
      label: '生产批次',
      prop: 'produceTaskBillNo',
      align: 'center', // 默认居中对齐
      width: 120
    },
    {
      label: '生产日期',
      prop: 'productionDate',
      align: 'center', // 默认居中对齐
      width: 120
    },
    {
      label: '仓库位置',
      prop: 'areaAndShelfName',
      align: 'center', // 默认居中对齐
      width: 120,
    },
    {
      label: '库存数量',
      prop: 'originalStockQuantity',
      align: 'center', // 默认居中对齐
      width: 120
    },
    {
      label: '盘点数量',
      prop: 'productTakeStockQuantity',
      align: 'center', // 默认居中对齐
      width: 120,
      formType: 'number',
      changeBtn: (value: any, row: any) => {
        if (value) {
          const takeStockNum = proxy.$count(`${row.productTakeStockQuantity || 0}-${row.originalStockQuantity || 0}`)
          if (takeStockNum > 0) {
            //盘盈
            row.takeStockResult = 2
          } else if (takeStockNum < 0) {
            //盘亏
            row.takeStockResult = 3
          } else {
            //持平
            row.takeStockResult = 1
          }
          row.gainorLossQuantity = takeStockNum
        } else {
          row.takeStockResult = 0
          row.gainorLossQuantity = null
        }
        row.isTakeStockName = takeStockType[row.takeStockResult] || '待盘'
      }
    },
    {
      label: '盘点单价',
      prop: 'productPrice',
      align: 'center', // 默认居中对齐
      width: 120,
    },
    {
      label: '盘点总价',
      prop: 'productAmount',
      align: 'center', // 默认居中对齐
      width: 120,
      value: (row: any) => {
        if (!row.productTakeStockQuantity) {
          row.productTakeStockQuantity = row.originalStockQuantity
        }
        let _productAmount: any = proxy.$count(`${row.productTakeStockQuantity || 0}*${row.productPrice || 0}`)
        row.productAmount = _productAmount
        return _productAmount
      }
    },
    {
      label: '盘点结果',
      prop: 'takeStockResultName',
      align: 'center', // 默认居中对齐
      width: 80,
      formType: 'tag',
      formKey: 'takeStockResult',
      options: [
        {
          label: '待盘',
          value: 0,
          type: 'info'
        },
        {
          label: '持平',
          value: 1,
          type: ''
        },
        {
          label: '盘盈',
          value: 2,
          type: 'success'
        },
        {
          label: '盘亏',
          value: 3,
          type: 'danger'
        },
      ]
    },
    {
      label: '盈亏数量',
      prop: 'gainorLossQuantity',
      align: 'center', // 默认居中对齐
      width: 80,
      value: (row: any) => {
        let _num: any = null
        if (row.productTakeStockQuantity || row.productTakeStockQuantity === 0) {
          _num = row.productTakeStockQuantity - row.originalStockQuantity
        }
        return _num || _num === 0 ? _num : '--'
      }
    },
    {
      label: '备注',
      prop: 'productTakeStockDetailRemark',
      align: 'center', // 默认居中对齐
      width: null, // 没有指定宽度
      formType: 'text',
    }
  ],
  type: [
    {
      label: '全部',
      value: -1
    },
    {
      label: '待盘点',
      value: 0
    },
    {
      label: '持平',
      value: 1
    },
    {
      label: '盘盈',
      value: 2
    },
    {
      label: '盘亏',
      value: 3
    }
  ]
});
const isEdit = ref(true)
//添加关联单明细
const getNumber = (type: any) => {
  let count = data.form.details.reduce((accumulator: number, current: any) => {
    return current.takeStockResult === type || type === -1 ? accumulator + 1 : accumulator;
  }, 0);
  return count
}
const takeStockType: any = {
  0: '待盘',
  1: '持平',
  2: '盘盈',
  3: '盘亏',
}
//获取数据
const getForm = async () => {
  const _query: any = route.query
  setLoading()
  //是否新建
  if (!!!_query.code) {
    proxy.$api.FinishedProduct.GetFinishedProductStockPageList({
      "pageIndex": 1,
      "pageSize": 99999,
      "queryDataBaseFiled": "",
      "likeWords": "",
      "beginTime": "",
      "endTime": "",
      "productNo": "",
      "onlyStocked": -1,
      "endProductionDate": ""
    })
      .then((res: any) => {
        data.form.details = proxy.$flattenObjectArray(res.list, 'details', (el: any) => {
          return {
            productTakeStockDetailCode: el.productTakeStockDetailCode,
            productTakeStockCode: el.productTakeStockCode,
            productTakeStockDetailRemark: el.productTakeStockDetailRemark,
            productStockNo: el.productStockNo,
            originalStockQuantity: el.stockQuantity,
            productNumber: el.productNumber,
            productName: el.productName,
            productLayout: el.productLayout,
            productSpecificationName: el.productSpecificationName,
            customerName: el.customerName,
            areaAndShelfName: `${el.wareHouseAreaName}/${el.areaSheltName}`,
            produceTaskBillNo: el.produceTaskBillNo,
            productionDate: proxy.$day(el.productionDate),
            productTakeStockState: el.productTakeStockState,
            takeStockResult: 0,
            productTakeStockQuantity: null,
          }
        })
      })
      .catch(() => { });
    data.loading = false
    return
  }
  proxy.$api.ProductTakeStock.GetProductTakeStock({
    code: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = ['1', '2'].includes(_query.type)
      data.form = {
        ...res,
        details: res.details.map((el: any) => {
          let takeStockResult = 0
          switch (el.productTakeStockState) {
            case '盘平':
              takeStockResult = 1
              break;
            case '盘赢':
              takeStockResult = 2
              break;
            case '盘亏':
              takeStockResult = 3
              break;
          }
          return {
            ...el,
            productionDate: proxy.$day(el.productionDate),
            takeStockResult: takeStockResult,
            takeStockResultName: takeStockType[takeStockResult] || '待盘'
          }
        })
      }
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
const saveBtn = (form: any, isConfirm: boolean = false) => {
  setLoading('正在保存数据，请稍等')
  const _form: any = {
    productTakeStockCode: form.productTakeStockCode, // 
    productTakeStockRemark: form.takeStockRemark, // 备注
    details: form.details.map((el: any) => (
      {
        productStockNo: el.productStockNo, // 库存code
        originalStockQuantity: el.originalStockQuantity, // 原库存
        productTakeStockQuantity: el.productTakeStockQuantity, // 盘点库存
        productTakeStockDetailRemark: el.productTakeStockDetailRemark, // 盘点备注说明
      }
    ))
  }
  // return
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.ProductTakeStock.AddProductTakeStock(_form)
        .then((res: any) => {
          if (isConfirm) {
            _sun()
          } else {
            sendMsg('save', true);
            router.push({
              query: {
                type: 2, //页面类型
                code: res.productTakeStockCode, //
              }
            });
            setTimeout(() => {
              getForm();
            }, 100);
          }
        })
        .catch(() => {
          data.loading = false
        });
      break;
    case '2'://编辑
      proxy.$api.ProductTakeStock.UpdateProductTakeStock(_form)
        .then((res: any) => {
          data.loading = false
          if (isConfirm) {
            _sun()
          } else {
            sendMsg('save', true);
          }
        })
        .catch(() => {
          data.loading = false
        });
      break;
    default:
      break;
  }
  function _sun() {
    closeBtn('保存成功')
  }
};
const closeBtn = (message?: string) => {
  if (message) {
    proxy.$message(message)
  }
  data.loading = false
  sendMsg('save', true);
  // getForm()
  window.close();
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};
// 导出数据
const exportBtn = () => {
  setLoading()
  proxy.$exportData(
    {
      thead: data.thead,
      tbody: data.form.details,
      fileName: '盘点明细',
    },
    data,
  );
};
onMounted(() => {
  getForm();
});
</script>
